package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.User;
import com.zja.service.Impl.UserServiceImpl;
import com.zja.service.UserService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;
/**
 * @author JA
 * @date: 2025/5/5
 * description: 修改用户基本信息
 */
@WebServlet("/api/user/updateInfo")
public class UpdateUserInfoServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User inputUser = ServletUtil.readJsonBody(req, User.class);

        //查重邮箱
        User existing = userService.getUserByEmailExcludeId(inputUser.getEmail(), inputUser.getId());
        if (existing != null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("该邮箱已被注册"));
            return;
        }

        // 更新
        User toUpdate = new User();
        toUpdate.setId(inputUser.getId());
        toUpdate.setEmail(inputUser.getEmail());
        toUpdate.setAvatar(inputUser.getAvatar());
        toUpdate.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        boolean success = userService.updateInfo(toUpdate);
        ServletUtil.writeJsonResponse(resp, success ? JsonResponse.success("更新成功") : JsonResponse.error("更新失败"));
    }
}
